<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="department" v-if="customerDepthForDepartment">部门</el-menu-item>
      <el-menu-item index="all" v-if="customerDepthForAll">全部</el-menu-item>
    </el-menu>

    <div style="margin-top:40px">
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="客户编号：">
           <el-input v-model="listQuery.customerNumber" placeholder="请输入内容" clearable></el-input>
        </el-form-item>

        <el-form-item label="客户名称：">
          <el-select
            clearable
            v-model="listQuery.customerName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod1"
            :loading="customerLoading">
            <el-option
              v-for="item in customerList"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.customerName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开发阶段：">
          <el-select  v-model="listQuery.stepId" placeholder="请选择" clearable multiple >
            <el-option v-for="item in developStepList"  :value="item.stepId" :label="item.stepName" :key="item.stepId"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="负责人：" v-if="listQuery.tab !='my'">
          <el-select v-model="listQuery.chargeId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="品类牌号：" >
          <el-input v-model="listQuery.goodsSn" placeholder="请输入内容" clearable></el-input>
        </el-form-item>

        <el-form-item label="替换牌号：" >
          <el-input v-model="listQuery.replaceGoodsSn" placeholder="请输入内容" clearable></el-input>
        </el-form-item>

        <el-form-item label="采购渠道：" >
          <el-select v-model="listQuery.supplierName"  placeholder="请选择" clearable>
            <el-option label="聚合厂" value="聚合厂"></el-option>
            <el-option label="贸易商" value="贸易商"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户分类：">
          <el-select v-model="listQuery.customerNewType" clearable multiple style="width:150px;">
            <el-option
              v-for="item in customerTypeList"
              :key="item.cddValue"
              :label="item.cddValue"
              :value="item.cddValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在地区：">
          <el-select v-model="listQuery.areaId1" placeholder="请选择省" @change="changeAreaId1" style="width:120px" clearable>
            <el-option v-for="item in areaList"  :key="item.areaId" :label="item.areaName"  :value="item.areaId" ></el-option>
          </el-select>
          <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-if="listQuery.areaId1" style="width:120px" clearable>
            <el-option v-for="item in areaList[areaIndex1]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
          </el-select>
          <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-else style="width:120px" clearable></el-select>
          <el-select v-model="listQuery.areaId3" placeholder="请选择区" style="width:120px" v-if="listQuery.areaId2" clearable>
            <el-option v-for="item in areaList[areaIndex1]['areaChildList'][areaIndex2]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
          </el-select>
          <el-select v-model="listQuery.areaId3" placeholder="请选择区" v-else style="width:120px"></el-select>
        </el-form-item>

        <el-form-item label="未成交时间：">
          <el-select v-model="listQuery.lastOrderTimeType" clearable multiple style="width:150px;">
            <el-option label="4个月以上" :value="4"> </el-option>
            <el-option label="5个月以上" :value="5"> </el-option>
            <el-option label="6个月以上" :value="6"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="成交时间：">
          <el-date-picker
            v-model="listQuery.orderDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList1()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        :span-method="objectSpanMethod"
        v-loading="listLoading1"
        :data="tableData1"
        max-height="460"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column  label="客户编号" min-width="200" align="center" header-align="center" prop="customerNumber">
          <template slot-scope="scope">
            <el-link @click="toDetail(scope.row)" type="primary" style="white-space: normal;">
              {{scope.row.customerNumber}}
            </el-link>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName" style="white-space: normal;">{{scope.row.customerName}}</div>
            <div style="padding-top: 5px">
              <crm-tag :item="item" v-for="item in scope.row.customerTag" :key="item.tagName" style="margin-bottom:4px;margin-right:4px"></crm-tag>
            </div>

          </template>
        </el-table-column>
        <el-table-column
          prop="sonName"
          label="子客户"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.isShowCustomerName">
              <div v-for="(item,index) in scope.row.sonName" :key="index" style="line-height: 16px;white-space: normal;">
                {{ item }}
              </div>
            </div>
            <div v-else>
              <div v-for="(item,index) in scope.row.sonCustomerNumber" :key="index" style="line-height: 16px;white-space: normal;">
                {{ item }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="customerNewType"
          label="客户分类"
          min-width="200"
          align="center">
          <template slot-scope="scope">
              {{scope.row.customerNewType}}
          </template>
        </el-table-column>
        <el-table-column
          prop="stepName"
          label="开发阶段"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.stepName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="负责人"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="customerOrderGoodsNum"
          label="历史总销量"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.customerOrderGoodsNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="categoryName"
          label="品类"
          min-width="100"
          align="center">
          <template slot-scope="scope">
              {{scope.row.categoryName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsSn"
          label="牌号"
          min-width="150"
          align="center">
          <template slot-scope="scope">
              <el-tooltip placement="bottom" effect="light">
                <div slot="content" style="max-width: 400px"> <span v-if="scope.row.goodsSn">{{scope.row.goodsSn.join(",")}}</span> </div>
                <div style="padding:0 10px;width:100%; white-space: nowrap;  overflow: hidden; text-overflow: ellipsis;text-align: left">
                  <span v-if="scope.row.goodsSn">{{scope.row.goodsSn.join(",")}}</span>
                </div>
              </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="monthUseNum"
          label="月使用量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
              {{scope.row.monthUseNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="monthOrderGoodsNum"
          label="本月销售量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.monthOrderGoodsNum}}
          </template>
        </el-table-column>
        <el-table-column
          label="销量占比"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.monthUseNum">{{(scope.row.monthOrderGoodsNum / scope.row.monthUseNum *100).toFixed(2)}}%</span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="monthShipNum"-->
<!--          label="本月出库量"-->
<!--          min-width="100"-->
<!--          align="center">-->
<!--          <template slot-scope="scope">-->
<!--              {{scope.row.monthShipNum}}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          prop="monthShipPerProfit"
          label="吨毛利"
          min-width="100"
          align="center">
          <template slot-scope="scope">
              {{scope.row.monthShipPerProfit}}
          </template>
        </el-table-column>
        <el-table-column
          porp="replaceGoodsSn"
          label="替换牌号"
          min-width="150"
          align="center">
          <template slot-scope="scope">
              <el-tooltip placement="bottom" effect="light">
                <div slot="content" style="max-width: 400px"> <span v-if="scope.row.replaceGoodsSn"> {{scope.row.replaceGoodsSn.join(",")}}</span></div>
                <div style="padding:0 10px;width:100%; white-space: nowrap;  overflow: hidden; text-overflow: ellipsis;text-align: left">
                  <span v-if="scope.row.replaceGoodsSn">{{scope.row.replaceGoodsSn.join(",")}}</span>
                </div>
              </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="supplierName"
          label="采购渠道"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.supplierName">{{scope.row.supplierName.join(",")}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="competitor"
          label="竞对名称"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.competitor">{{scope.row.competitor.length == 0 ? "后续确认" :scope.row.competitor.join(",")}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="setting"
          label="操作"
          fixed="right"
          align="center"
          min-width="100">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.isCanEdit"
              type="text"
              @click="showAddGoods(scope.row)"
              size="mini">编辑产品
            </el-button>
            <el-button
              v-if="listQuery.tab == 'my'"
              style="margin-left: 0"
              type="text"
              @click="showGj(scope.row)"
              size="mini">新增跟进
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count1">
      </el-pagination>
    </div>

    <addUseGoods ref="addUseGoods" @update="getList1"></addUseGoods>

    <!--新增跟进-->
    <addGj ref="addGj" @getList="getList1"></addGj>

  </div>
</template>
<script>

import {getOrderUsersList,getCustomerOption,getConfigList,getAddressList,getCustomerSetting} from '@/api/partner'
import {customerListByUseGoods} from '@/api/company.js'
import {getDevelopStepListAPI} from '@/api/fms.js'

import addGj from './components/addGj';
import addUseGoods from './components/addUseGoods';
import crmTag from "@/views/components/crmTag";
import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  "tab" : "my",
  "customerId" : '',
  "customerNumber" : "",
  "customerName" : "",
  "chargeId" : '', //负责人
  "goodsSn" : "", //牌号
  "replaceGoodsSn" : "", //替换牌号
  "supplierName" : "",  //采购渠道
  customerNewType:[],
  areaId1: '',//省ID
  areaId2: '',//市
  areaId3:'',//区
  lastOrderTimeType:[],
  stepId:[],
  orderDate:[],
  "pageNum" : 1,
  "pageSize" : 10
};



export default {
  name: "customerDepth",
  data(){
    return {
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData1: [],
      count1: 0,
      listLoading1: false,
      userOptionList:[],


      customerList:[],
      customerLoading:false,
      customerTypeList:[],
      areaList:[],
      areaIndex1:null,
      areaIndex2: null,
      developStepList:[]
    }
  },
  components:{
    addGj,
    addUseGoods,
    crmTag
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    customerDepthForAll (){
      if(this.roles.indexOf("customerDepthForAll") != -1){
        return true
      }else{
        return false
      }
    },
    customerDepthForDepartment (){
      if(this.roles.indexOf("customerDepthForDepartment") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.getUserOptionList();
    this.getCustomerType()
    this.getList1();
    this.getAddressListData()
    this.getCustomerSettingList();
  },
  filters: {



  },
  methods:{
    //获取客户配置
    getCustomerSettingList() {
      getDevelopStepListAPI().then((res) => {
        this.developStepList = res.list;
      })
    },
    //获取省市区列表
    getAddressListData(){
      getAddressList().then((res)=>{
        this.areaList = res;
      })
    },
    //切换省
    changeAreaId1(item) {
      this.areaIndex1 = this.areaList.findIndex((el)=>{
        return item == el.areaId
      });
      this.areaIndex2 = null;
      this.listQuery.areaId2 = '';
      this.listQuery.areaId3 = '';
    },
    //切换市
    changeAreaId2(item){
      this.areaIndex2 = this.areaList[this.areaIndex1]['areaChildList'].findIndex((el)=>{
        return item == el.areaId
      });
      this.listQuery.areaId3 = '';
    },
    //获取客户分类列表
    getCustomerType(){
      getConfigList({status:1}).then((res)=>{
        let customerType = res.find((el)=>{
          return  el.cdtCode == 'customer_new_type'
        })
        this.customerTypeList = customerType ? customerType.data : []
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }){
      let bhName = ['customerNumber','sonName','userName','customerOrderGoodsNum','customerNewType','setting','stepName']
      if(bhName.indexOf(column.property) != -1){
        if (row.isHb) {
          return {
            rowspan: row.hbnum,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else{
        return {
          rowspan: 1,
          colspan: 1
        };
      }
    },
    //去客户详情页
    toDetail(item) {
      let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
      window.open(routeData.href);
    },
    //新增跟进
    showGj(item){
      this.$refs.addGj.showTracking(item,'add','my')
    },
    showAddGoods(item){
      this.$refs.addUseGoods.showPop(item.customerId)
    },
    //获取客户列表
    remoteMethod1(query) {
      if(query && query!= ''){
        this.customerLoading = true;
        getCustomerOption({keywords:query}).then(response => {
          this.customerList = response;
          this.customerLoading = false;
        }).catch(()=>{
          this.customerLoading = false;
        });
      }
    },

    handleSelect(key){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = key
      this.handleSearchList1()
    },

    //获取列表
    getList1(){
      this.listLoading1 = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery));
      customerListByUseGoods(listQuery).then(response => {
        this.tableData1 = []
        response.list.forEach((el,index)=>{
          el.useGoodsList.forEach((ee,index2)=>{
            let c={}
            for(let key1 in el){
              if(key1 != 'useGoodsList'){
                c[key1] = el[key1]
              }

            }
            for(let key2 in ee){
              c[key2] = ee[key2]
            }
            if(index2 == 0){
              c.hbnum = el.useGoodsList.length
              c.isHb = true
            }else{
              c.hbnum = 0
              c.isHb = false
            }
            this.tableData1.push(c)
          })
          if(el.useGoodsList.length == 0){
            let c={}
            for(let key1 in el){
              if(key1 != 'useGoodsList'){
                c[key1] = el[key1]
              }
            }
            c.hbnum = 1
            c.isHb = true
            this.tableData1.push(c)
          }
        })
        this.count1 = response.count;
        this.listLoading1 = false;
      }).catch(()=>{
        this.listLoading1 = false;
      });
    },

    handleSizeChange1(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList1();
    },
    handleCurrentChange1(val){
      this.listQuery.pageNum = val;
      this.getList1();
    },

    handleSearchList1(){
      this.listQuery.pageNum = 1;
      this.getList1();
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },



  },
}
</script>

<style scoped lang="scss">
.upload-div{
  text-align: center;
  position:relative;
  #upload{

    opacity: 0;
    position: absolute;
    z-index: 1;
    width:154px;
    height:40px
  }
}
.title-tab{
  border-radius: 8px;
  background: #eee;
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
  line-height: 20px;
  padding: 0 5px;
  color: #666;
}
</style>
